package com.longer.demo.framework.validator;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @program: mybatis
 * @description:
 * @author: SunBiaoLong
 * @create: 2019-01-14 10:47
 **/
@Component
public class MyValidator implements InitializingBean {
	private Validator validator;
	public ValidationResult validate(Object bean){
		final ValidationResult validationResult = new ValidationResult();
		Set<ConstraintViolation<Object>> constraintViolationSet =validator.validate(bean);
		//检查是否有错误
		if (constraintViolationSet.size()>0){
			//有错误
			validationResult.setHasErrors(true);
			constraintViolationSet.forEach(constraintViolation->{
				String errorMsg = constraintViolation.getMessage();
				String propertyName = constraintViolation.getPropertyPath().toString();
				validationResult.getErrorMsgMap().put(propertyName, errorMsg);
			});
		}
		return validationResult;

	}

	@Override
	public void afterPropertiesSet() throws Exception {
		//将hibernate validator 通过工厂的初始化方式使其实例化
		validator = Validation.buildDefaultValidatorFactory().getValidator();
	}
}
